#include "except.h"
#include <stdio.h>
#include <assert.h>


#define DO_RAISE
// #undef DO_RAISE // 取消注释，测试不抛异常的流程


// 一般正式使用时，会有单独的地方定义项目中的异常。
static Except_T e1 = {"e1 except"};
static Except_T e2 = {"e2 except"};


void 
raise_test(Except_T *ex) {
#ifdef DO_RAISE
	printf(" raise ex:%s\n", ex->msg);
	RAISE(*ex);
#endif
	printf("***never come here\n");
}

#define RAISE_TEST(ex) raise_test(&ex); printf("some code not exec\n");

void
simple_test() {
	printf("come to simple test\n");
TRY
	printf("--simple test try-else\n");
	RAISE_TEST(e1)
ELSE
 	printf("default for except, ex:%s, file:%s, line:%d\n", EXCEPT_MSG, EXCEPT_FILE, EXCEPT_LINE);
END_TRY
	printf("simple test ends\n");

TRY
	printf("\n--simple test try except\n");
	RAISE_TEST(e2)
EXCEPT(e1)
	printf("catch e1 except:%s\n", e1.msg);
EXCEPT(e2)
 	printf("catch e2 except:%s\n", e2.msg);
END_TRY
	printf("simple test ends\n");

TRY
	printf("\n--simple test try finally\n");
FINALLY
 	printf("finally with no except\n");
END_TRY

TRY
	printf("\n--simple test try finally\n");
	RAISE_TEST(e1)
EXCEPT(e1)
	printf("catch e1 except:%s\n", e1.msg);
FINALLY
 	printf("finally with except\n");
END_TRY
	printf("simple test ends\n");

TRY
	printf("\n--simple test try-else with no except\n");
ELSE
 	printf("default for except\n");
END_TRY
	printf("simple test ends\n");

	assert(__ex_frame == NULL);
}

void 
func() {
TRY
	printf("come to func\n");
	RAISE_TEST(e1)
FINALLY
	printf("clean func\n");
END_TRY
}

void 
nest_test() {
	printf("come to nest test\n");
TRY
	func();
ELSE
	printf("catch except for default\n");
END_TRY
	printf("nest test ends\n");

	assert(__ex_frame == NULL);
}

void
return_test() {
TRY
	printf("come to return test, then return\n");
	RETURN
	printf("never come here\n");
FINALLY
 	printf("finally for return\n");
END_TRY
	printf("some code not exec for return\n");
	
	assert(__ex_frame == NULL);
}

void
reraise_func() {
TRY
	printf("raise except here\n");
	RAISE_TEST(e1)
ELSE
 	printf("default for except then reraise\n");
 	RERAISE;
END_TRY
	printf("this func never come here\n");
}

void
reraise_test() {
TRY
	printf("come to reraise test\n");
	reraise_func();
	printf("never come here\n");
ELSE
 	printf("default for except, ex:%s, file:%s, line:%d\n", EXCEPT_MSG, EXCEPT_FILE, EXCEPT_LINE);
END_TRY
	printf("reraise test ends\n");
	
	assert(__ex_frame == NULL);	
}

int
main() {
	simple_test();
	printf("\n\n");
	nest_test();
	printf("\n\n");
	return_test();
	printf("\n\n");
	reraise_test();
	printf("\nexcept test pass\n");
	fflush(stdout);
	return 0;
}
